#include <stdio.h>

#include "pb_encode.h"
#include "pb_decode.h"
#include "message.pb.h"

int main(void)
{
    uint8_t buffer[Example_size + 1] = {};
    size_t message_length = 0;
    bool status = false;

    printf("nanopb-version[%s]\n", NANOPB_VERSION);

    /* Encode */
    {
        Example message = Example_init_zero;
        pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
        message.has_value = true;
        message.value = 123;
        strncpy(message.str, "hello", sizeof(message.str));
        message.names_count = 2;
        for (pb_size_t i = 0; i < message.names_count; ++i)
        {
            snprintf(message.names[i], sizeof(message.names[i]), "name%u", i);
        }
        status = pb_encode(&stream, Example_fields, &message);
        message_length = stream.bytes_written;
        if (!status)
        {
            printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
            return 1;
        }

        printf("Encode Success, len[%zd]!\n", message_length);
    }

    /* Decode */
    {
        Example message = Example_init_zero;
        pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
        status = pb_decode(&stream, Example_fields, &message);
        if (!status)
        {
            printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
            return 1;
        }
        printf("Decode Success! \n");
        printf("message.has_value[%d], message.value[%u], message.str[%s]!\n", message.has_value, message.value, message.str);
        printf("message.names_count[%u]:\n", message.names_count);
        for (pb_size_t i = 0; i < message.names_count; ++i)
        {
            printf("\tmessage.names[%u]:[%s]\n", i, message.names[i]);
        }
    }

    return 0;
}
